<template>
  <div>
    <van-search
      v-model.trim="searchText"
      show-action
      label="地址"
      placeholder="请输入搜索关键词"
      background="#f66"
      @search="onSearch"
    >
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>
    <h5>搜索记录</h5>
    <div class="search-his">
      <div class="his" v-for="his in histories" @click="clickHis(his)" :key="his">
        {{his}}
      </div>
      <div class="zanwu" v-if="!histories.length">暂无</div>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      searchText: '',
      histories: localStorage.getItem('his') ? JSON.parse(localStorage.getItem('his')) : []
    }
  },
  methods: {
    clickHis (his) {
      this.$router.push({
        path: '/searchResult',
        query: {
          word: his
        }
      })
    },
    onSearch () {
      if (this.searchText === '') {
        this.$toast('不能为空')
        return
      }
      // 存历史记录
      // his
      // 先取 缓存 转换成数组 操作数组 操作完成之后再存进去
      const his = localStorage.getItem('his') ? JSON.parse(localStorage.getItem('his')) : []

      // 避免重复
      // his = [...new Set(his)]
      const index = his.indexOf(this.searchText)
      if (index != -1) {
        his.splice(index, 1)
      }
      his.unshift(this.searchText)
      // his.length = 5
      if (his.length > 5) {
        his.pop()
      }
      localStorage.setItem('his', JSON.stringify(his))
      // 跳转到结果页
      this.$router.push({
        path: '/searchResult',
        query: {
          word: this.searchText
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.search-his{
  display: flex;
  flex-wrap: wrap;
  .his{
    line-height: 30px;
    font-size:16px;
    padding:0 5px;
    border-radius: 15px;
    background: #ddd;
    margin:10px;
  }
}
</style>
